const Service = require('egg').Service
const SEND_COUPON_OR_RED_PACKET_KEY = `redis_activity_sendCouponOrRedPacketParam`
// const sendPrizeRecord =
module.exports = class SendPrize extends Service {
  /**
   *
   * @param {*} activityId           活动id
   * @param {*} combinationId        活动渠道关系id
   * @param {*} userId               用户id
   * @param {*} level                活动规则级别
   * @param {*} redPacketCount       每次发送红包的数量
   * @param {*} remainMon            投资金额
   * @param {*} buyWay               购买方式
   * @param {*} type                 发送类型 1 发送奖品 | 2发送机会（不分产品线）| 3 发送机会（分产品线）
   * @param {*} productId            产品id
   * @param {*} changeNum            机会数量
   * @param {*} changeId             机会id
   * @param {*} saveType             reds中机会保存类型
   */
  async send({
    activityId,
    combinationId,
    userId,
    level,
    redPacketCount,
    // redPaketMoney,
    remainMon,
    buyWay,
    type,
    productId = 0, //默认为0
    changeNum,
    changeId,
    saveType
  }) {

    // this里的对象里的一些对象
    let {
      ctx,
      service,
      app,
      logger
    } = this;
    // 参数校验
    // let paramsCheck =

    if (!ctx.helper.isNullFiled({
      activityId,
      combinationId,
      userId,
      level,
      redPacketCount
    })) {
      return false
    }

    try {
      let {
        activeInfo,
        rule
      } = await service.common.redisActiveInfo(activityId, level);

      if (!activeInfo || !rule || !rule.length) {
        logger.info(`发送失败，活动或者规则不存在,活动id=>${activityId}`);
        return false;
      }
      if (!ctx.helper.isEnd(activeInfo.start_time, activeInfo.end_time)) {
        logger.info(`活动已经结束`);
        return false
      };


      type = !type ? 1 : parseInt(type); // 默认发送奖品
      buyWay = !buyWay ? 1 : buyWay
      let result = null // 发送结果
      switch (type) {
        case 1: // 开始发平台奖品，自建奖品，零元购奖品
          for (let item of rule) {
            let goodType = item.goodType

            // console.log('%c gc_goodType=>: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', type);
            if (goodType == 1 || goodType == 2 || goodType == 3) { // 发送平台奖品
              result = await service.sendPrize.sendPlatform({
                _rewards: item,
                activityId,
                combinationId,
                userId,
                remainMon,
                changeId,
                productId,
                redPacketCount: redPacketCount || 1, // 默认一次发送一个
                saveType,
              });
            } else if (goodType == 4) { // 发送自建奖品
              // console.log('发送自建奖品---------------------xxxxxxxxx')
              result = await service.sendPrize.sendSelfPrize({
                userId,
                _rewards: item,
                activityId,
                combinationId,
                changeId,
                remainMon,
                productId,
                redPacketCount: redPacketCount || 1,
                saveType
              })

            } else if (goodType == 5) { // 发送0元购奖品

            }
          }
          break;
        case 2:
          break;
        case 3:
          break;


      }
      return result

    } catch (error) {
      console.log(error, 'ererewrwerwerwer')
    }

  }

  /**
   *发送平台奖品
   *
   * @param {*} rewards             Object 奖品配置
   * @param {*} activityId          活动id
   * @param {*} combinationId       渠道关系id
   * @param {*} remainMon           用户投资金额
   * @param {*} productId           投资产品线
   * @param {*} userId              用户id
   * @param {*} changeId            抽奖所消耗的机会id
   * @param {*} redPacketCount      发送红包的数量
   * @param {*} requestNo           请求串号
   * @param {*} isRepeatSend        是否为重发
   * @param {*} saveType            redis中机会记录保存类型，默认按天分1 |  所有记录放在一起2
   *
   */
  async sendPlatform({
    _rewards,
    activityId,
    combinationId,
    userId,
    remainMon,
    productId,
    changeId,
    redPacketCount,
    requestNo,
    isRepeatSend,
    saveType,
  }) {
    // this里的对象里的一些对象
    // console.log(userId, '_rewards-------------')
    let {
      ctx,
      service,
      app,
      logger
    } = this;

    let sendResult = { // 返回结果
      state: false,
      redpacks: null,
      coupon: null
    };

    // 参数校验
    try {
      let rewards = {
        id: parseInt(_rewards.id),
        type: parseInt(_rewards.goodType),
        count: parseInt(redPacketCount),
      };
      if (!ctx.helper.isNullFiled(rewards)) {
        return false
      };

      rewards.money = remainMon || 0;
      // 生成请求串号
      requestNo = requestNo ? requestNo : await ctx.helper.sendPrizeRequestNo()

      let params = {
        method: 'activity.system.boon.send',
        userid: userId,
        activity_id: activityId,
        serial_no: requestNo,
        rewards: [rewards]
      };
      let key = `${SEND_COUPON_OR_RED_PACKET_KEY}:${activityId}:${requestNo}-${userId}`
      await app.redis.setex(key, 86400, JSON.stringify(params));
      // 在数据库中插入一条奖品记录
      await service.common.insertOne({
        tableName: 'hd_send_user_award_platform',
        params: {
          userid: userId,
          serial: `'${requestNo}'`,
          good_type: rewards.type,
          good_id: rewards.id,
          send_total: rewards.count,
          status: 1,
          activity_id: activityId,
          combination_id: combinationId
        }
      });
      // 调用主站发送接口
      let result = await service.http.Jinr(params);

      if (result.code !== 1000200 || !result.data) {
        logger.info(`用户${userId},活动${activityId},奖品${rewards.id}发送失败`);
        // return true; // 因为会进行补发，所以认为发送成功
        sendResult.state = true;
        return sendResult
      }

      let {
        redpacks,
        coupon
      } = result.data;
      let updataWhere = {
        activity_id: activityId,
        combination_id: combinationId,
        userid: userId,
        serial: `'${requestNo}'`
      };
      if (redpacks instanceof Array && redpacks.length) { // 体验金 | 现金
        // 更新奖品表状态为发送成功
        Object.assign(sendResult, {
          state: true,
          redpack: redpacks[0]
        });
        let value = {
          'money': `'${redpacks[0].redpackmoney}'`,
          'status': 2,
          'status_error': `'${result.msg || '发送成功'}'`
        }
        await service.common.upData({
          tableName: 'hd_send_user_award_platform',
          value,
          where: updataWhere
        });
        await app.redis.del(key);

      }

      if (coupon instanceof Array && coupon.length) { // 发送卡卷
        Object.assign(sendResult, {
          state: true,
          coupon: coupon[0]
        });

        await service.common.upData({
          tableName: 'hd_send_user_award_platform',
          value: {
            'status': 2,
            'status_error': `'${result.msg || '发送成功'}'`
          },
          where: updataWhere
        });
        await app.redis.del(key);
      }
      // 关联奖品id
      if (sendResult.state) { // 发送成功
        // 将奖品信息写入redis
        service.sendPrize.addSendPrizeRecord({
          userId,
          activityId,
          combinationId,
          remainMon,
          productId,
          rewards,
          saveType,
          money: sendResult.redpack ? sendResult.redpack.redpackmoney : 0
        });
        if (changeId) {
          let upDataRes = await service.selfPrize.upDataChange({
            activityId,
            combinationId,
            userId,
            productId,
            isRepeatSend,
            rewardId: rewards.id
          })
          if (upDataRes instanceof Object && !upDataRes.state) {
            sendResult.errMsg = upDataRes.errMsg
          }
        }
      }
      return sendResult;

    } catch (error) {
      console.log(error, 'error')
      sendResult.state = false;
      return sendResult
    }


  }

  /**
   *
   * @param {*} userId           用户id
   * @param {*} rewards          奖品配置
   * @param {*} activityId       活动id
   * @param {*} combinationId    渠道关系id
   * @param {*} changeId         机会id
   * @param {*} remainMon        用户投资金额
   * @param {*} saveType         保存类型
   * @param {*} productId        产品id
   *
   */
  async sendSelfPrize({ userId, _rewards, activityId, combinationId, changeId, remainMon, saveType, productId, redPacketCount }) {
    const { ctx, app, service } = this;
    // let sendResult = { // 返回结果
    //   state: false,
    //   selfPrize: null,
    //   errMsg: null
    // };
    // 参数校验
    let rewards = {
      id: parseInt(_rewards.id),
      type: parseInt(_rewards.goodType),
      count: parseInt(redPacketCount),
    };
    if (!ctx.helper.isNullFiled(rewards)) {
      // return false
      // sendResult.state = false;
      // sendResult.errMsg = '参数校验失败';
      // return sendResult
      return {
        state: false,
        errMsg: '参数校验失败'
      }
    };

    // 判断自建奖品是否存在
    let goods = await service.common.findOne({
      filed: ['id'],
      tableName: 'hd_award_config',
      where: { id: rewards.id }
    })
    // console.log(goods, 'goods----goods');
    if (!goods.id) {
      return {
        state: false,
        errMsg: '发送失败，自建奖品不存在'
      }
    }
    //先扣除机会
    if (changeId) { //机会id存在
      let upDataRes = await service.sendPrize.upDataChange({
        activityId,
        combinationId,
        userId,
        productId,
        rewardId: rewards.id
      })
      if (!upDataRes || (upDataRes instanceof Object && !upDataRes.state)) {
        return {
          state: false,
          errMsg: upDataRes.errMsg
        }

      }
    }
    // 查询用户信息
    let userInfo = await service.common.getUserInfo(userId)
    console.log(userInfo, '---------------123123123123')
    if (!userInfo || !userInfo.userid) {
      return {
        state: false,
        errMsg: '发送失败，用户不存在'
      }
    }
    // 在数据库中插入一条记录
    let params = {
      activity_id: activityId,
      combination_id: combinationId,
      award_id: rewards.id,
      receive_method: 2,
      receive_url: `'http://www.huodonghezi.com'`,
      receive_uid: userId,
      receive_tel: `'${userInfo.mobile}'`
    }
    let insertRes = await service.common.insertOne({
      tableName: 'hd_receive_award_user',
      params
    })
    console.log(insertRes, 'insertRes734218934982349823');
    return insertRes && insertRes[0] ? {
      state: true,
      data: { prizeRecordId: insertRes[0] },
      errMsg: 'success',
    } : { state: false, errMsg: '自建奖品入库失败' }
  }




  /**
   *
   * @param {*} userId        用户id
   * @param {*} requestNo     请求串号
   * @param {*} good_id       奖品id
   * @param {*} saveType      存储类型    1 按天分 | 不传不按天分
   * @param {*} money         奖品金额
   * @param {*} remainMon     投资金额
   * @param {*} activity      活动id
   * @param {*} combinationId 渠道关系id
   * @param {*} rewards       奖规则品信息
   * @param {*} productId     投资产品线
   * @param {*} name          奖品名称    （仅自建奖品需传）
   */
  async addSendPrizeRecord({
    userId,
    requestNo,
    saveType,
    money,
    remainMon,
    activity,
    combinationId,
    rewards,
    productId,
    name
  }) {
    let {
      ctx,
      service,
      app,
      logger
    } = this;
    try {
      let key = app.config.redisKey.sendPrizeRecord
      let recordKey = `${key}:${activity}:${combinationId}`;
      if (!saveType) {
        let day = moment(Date.now()).format('YYYYMMDD')
        recordKey = `${recordKey}:${day}`;
      }

      // let prizeName = {
      //   1: '体验金',
      //   2: '现金'
      // };
      let prizeName = rewards.type > 2 ? ['体验金', '现金'][rewards.type] : rewards.prizeName;
      let params = {
        userId,
        good_type: rewards.type,
        good_id: rewards.id,
        money,
        remainMon,
        username: '',
        mobile: '',
        province_name: '',
        productId,
        timestamp: Date.now(), // 防止重复
        prizeName,
        time: moment(Date.now()).format('MM/DD HH:mm'),
        times: moment(Date.now()).format('YYYY/MM/DD HH:mm'),
      }
      // 获取用户信息
      let userInfo = await service.common.getUserInfo(userId);
      if (userInfo) {
        params.username
      }

    } catch (error) {

    }


  }

  /**
   * 更新机会，适用于分产品线的抽奖
   * @param {*} activityId
   * @param {*} combinationId    渠道关系id
   * @param {*} userId           用户id
   * @param {*} productId        产品id
   * @param {*} isRepeatSend     是否属于重发
   * @param {*} rewardId         奖品id
   * @param {*} changeId         机会id
   */
  async upDataChange({ activityId, combinationId, userId, productId, isRepeatSend, rewardId }) {
    const { app, service } = this;
    let userChangeKey = app.config.redisKey.userChangeKey + `${activityId}:${combinationId}:${userId}:${productId}`;
    if (!isRepeatSend) { // 首次发送扣除一次机会，首发失败，补发不扣机会
      if (await app.redis.hincrby(userChangeKey, 'change_num', -1) < 0) { // 没有抽奖机会
        await app.redis.hset(userChangeKey, 'change_num', 0);
        // return false
        // sendResult.state = false;
        return {
          state: false,
          errMsg: '抽奖机会不足'
        }
      };
      await app.redis.hincrby(userChangeKey, 'used_num', 1);
    }
    // 更新机会表
    await service.common.upData({
      tableName: 'hd_user_order_lottery',
      value: {
        send_user_award_platform_id: rewardId,
        is_lottery: 1
      },
      where: {
        uolottery_id: changeId
      }
    })
    return {
      state: true,
      errMsg: 'success'
    }
  }

}